package com.sunwayworld.baseline.framework.utils;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.utils.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LimsDynamicDsHelper {

    private Map<String, DataSource> dataSourceMap = new ConcurrentHashMap<>();

    private static LimsDynamicDsHelper instance;
    private static int slowSqlLimit = 5000; //慢sql限值,毫秒
    ConcurrentHashMap<String,JdbcTemplate> jdbcMap = new ConcurrentHashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(LimsDynamicDsHelper.class);

    public static final LimsDynamicDsHelper getInstance() {
        if (instance == null) {
            synchronized (LimsDynamicDsHelper.class) {
                if (instance == null) {
                    instance = new LimsDynamicDsHelper();
                    Environment environment = ApplicationContextHelper.getBean(Environment.class);
                    slowSqlLimit = Integer.parseInt(environment.getProperty("slowSqlLimit", "5000"));
                }
            }
        }
        return instance;
    }

    public JdbcTemplate getJdbcTemplate(String userName, String password, String url, String driverClassName) {
        if(ObjectUtils.isEmpty(userName)){
            throw new InvalidDataException("请输入用户名");
        }
        if(ObjectUtils.isEmpty(password)){
            throw new InvalidDataException("请输入密码");
        }
        if(ObjectUtils.isEmpty(url)){
            throw new InvalidDataException("请输入数据库链接");
        }
        if(ObjectUtils.isEmpty(driverClassName)){
            throw new InvalidDataException("请输入数据库驱动");
        }
        String urlMd5 = MD5Util.getMD5Format(url);
        if(jdbcMap.containsKey(urlMd5)){
            return jdbcMap.get(urlMd5);
        }

        try {
            DriverManagerDataSource datasource = new DriverManagerDataSource();
            datasource.setUsername(userName);
            datasource.setPassword(password);
            datasource.setUrl(url);
            datasource.setDriverClassName(driverClassName);

            JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
            if (url.contains("mysql")){
                jdbcTemplate.queryForMap("select 1 from dual");
            }else if (url.contains("sqlserver")){
                jdbcTemplate.queryForMap("select SUM(1) from master.dbo.sysdatabases");
            }
            jdbcMap.put(urlMd5,jdbcTemplate);
            return jdbcTemplate;
        }catch (Exception s){
            s.printStackTrace();
            throw new InvalidDataException(s.getMessage());
        }
    }


    public List<Map<String, Object>> queryForList(JdbcTemplate jdbcTemplate,String sql, Object... args){
        if(jdbcTemplate==null){
            throw new RuntimeException("jdbcTemplate is null");
        }
        long start = System.currentTimeMillis();
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,args);
        long useTime = System.currentTimeMillis()-start;
        if(useTime>=slowSqlLimit){
            logger.warn("取数慢SQL耗时:{},返回数量={},执行SQL={}",useTime,list==null?0:list.size(),sql);
        }
        return list;
    }

    public static int getSlowSqlLimit() {
        return slowSqlLimit;
    }
}
